package replic.driver;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 
 * @author Leonardo Oliveira Moreira
 * 
 */
public class RepliCDriver implements Driver {

    static RepliCDriver singleton;

    static {
        singleton = new RepliCDriver();
        try {
            DriverManager.registerDriver(singleton);
        } catch (SQLException e) {
            throw new RuntimeException("Unable to register replic driver!");
        }
    }

    @Override
    public Connection connect(String url, Properties info) throws SQLException {
        if (!url.startsWith("jdbc:replic")) {
            return null;
        }
        String[] split = url.split("//");
        String[] s = split[1].split(":");
        String host = s[0];
        int port = 7777;

        if (s.length > 1) {
            port = Integer.parseInt(s[1].split("/")[0]);
        }
        info = new Properties(info);
        info.setProperty("databaseName", s[1].split("/")[1]);
        return new RepliCConnection(host, port, info);
    }

    @Override
    public boolean acceptsURL(String url) throws SQLException {
        return url != null && url.startsWith("jdbc:replic:");
    }

    @Override
    public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public int getMajorVersion() {
        return 1;
    }

    @Override
    public int getMinorVersion() {
        return 0;
    }

    @Override
    public boolean jdbcCompliant() {
        return false;
    }
    
}